/**
 * Created with IntelliJ IDEA.
 * User: http
 * Email: guobin@ebigdata.org
 * Date: 2017/8/1
 * Time: 10:57
 * To change this template use File | Settings | File Templates.
 */
import axios from 'axios'
import Vue from 'vue'
window.$HttpPendingList = []
let bol = ''
bol === 'mock' ? axios.defaults.baseURL = '192.168.2.74:8111' : axios.defaults.baseURL = '.'
// bol === 'mock' ? axios.defaults.baseURL = 'http://rap.xdbigdata.com/mockjsdata/25' : axios.defaults.baseURL = './'
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.interceptors.request.use(function (config) {
  Vue.prototype.$Progress.start()
  return config
}, function (error) {
  Vue.prototype.$Progress.fail()
  return Promise.reject(error)
})

// Add a response interceptor
axios.interceptors.response.use(function (response) {
  Vue.prototype.$Progress.finish()
  return response
}, function (error) {
  if (error.response.status === 401) {
    Vue.prototype.$message({
      message: '身份失效，请重新登录！',
      type: 'error'
    })
    // window.location.href = './#/login'
    window.location.href = 'http://172.16.16.102/zfca'
  }
  Vue.prototype.$Progress.fail()
  return Promise.reject(error)
})

export const GET = function (url) {
  const CancelToken = axios.CancelToken
  url = url + '?timestamp=' + Date.parse(new Date())
  const request = axios.get(url, {
    cancelToken: new CancelToken(function executor (c) {
      window.$HttpPendingList.push(c)
    })
  }).catch(function (thrown) {
    if (axios.isCancel(thrown)) {
      console.log('Request canceled')
    } else {
      // handle error
    }
    Vue.prototype.$Progress.fail()
  })
  return request
}

export const POST = function (url, query) {
  const CancelToken = axios.CancelToken
  const request = axios.post(url, query, {
    cancelToken: new CancelToken(function executor (c) {
      window.$HttpPendingList.push(c)
    })
  }).catch(function (thrown) {
    if (axios.isCancel(thrown)) {
      console.log('Request canceled')
    } else {
      // handle error
    }
    Vue.prototype.$Progress.fail()
  })
  return request
}

export const DELETE = function (url) {
  const CancelToken = axios.CancelToken
  const request = axios.delete(url, {
    cancelToken: new CancelToken(function executor (c) {
      window.$HttpPendingList.push(c)
    })
  }).catch(function (thrown) {
    if (axios.isCancel(thrown)) {
      console.log('Request canceled')
    } else {
      // handle error
    }
    Vue.prototype.$Progress.fail()
  })
  return request
}

export const PUT = function (url, query) {
  const CancelToken = axios.CancelToken
  const request = axios.put(url, query, {
    cancelToken: new CancelToken(function executor (c) {
      window.$HttpPendingList.push(c)
    })
  }).catch(function (thrown) {
    if (axios.isCancel(thrown)) {
      console.log('Request canceled')
    } else {
      // handle error
    }
    Vue.prototype.$Progress.fail()
  })
  return request
}
